package com.lemon.mask.strategy;

import com.google.common.collect.Maps;
import com.lemon.mask.annotation.DataMaskType;
import com.lemon.mask.enumeration.SensitiveType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author lemon
 * @version 1.0
 * @description: 数据脱敏策略
 * @date Create by lemon on 2020-07-06 11:09
 */
@Slf4j
@Component
public class DataMaskStrategyContext implements InitializingBean {
    @Autowired
    private List<DataMaskStrategy> maskStrategys;

    private static final Map<SensitiveType, DataMaskStrategy> MASK_STRATEGY_MAP = Maps.newHashMap();

    @Override
    public void afterPropertiesSet() throws Exception {
        maskStrategys.forEach(maskStrategy -> {
            DataMaskType maskType = maskStrategy.getClass().getAnnotation(DataMaskType.class);

            if (maskType == null) {
                log.error("Class[{}] must specify annotation [{}]", maskStrategy.getClass(), DataMaskType.class);
                return;
            }

            MASK_STRATEGY_MAP.put(maskType.sensitiveType(), maskStrategy);
        });
    }

    /**
     * @param sensitiveType
     * @return com.lemon.mask.strategy.DataMaskStrategy
     * @description 获取数据脱敏策略
     * @author lemon
     * @date 2020-07-06 11:15
     */
    public static DataMaskStrategy getDataMaskStrategy(SensitiveType sensitiveType) {
        return MASK_STRATEGY_MAP.get(sensitiveType);
    }
}
